package com.dhh.sky.service;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import org.json.JSONObject;
import android.app.IntentService;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import com.dhh.sky.R;
import com.dhh.sky.SDAApplication;
import com.dhh.sky.model.Operation;
import com.dhh.sky.model.SkyDriveObject;
import com.dhh.sky.util.CUtil;
import com.dhh.sky.util.Config;
import com.dhh.sky.util.Constant;
import com.dhh.sky.util.OperationManager;
import com.microsoft.live.LiveAuthClient;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveDownloadOperation;
import com.microsoft.live.LiveDownloadOperationListener;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveStatus;

public class OpenOperationService extends IntentService {
	private OperationManager om;
	private Operation op;
	private SDAApplication app;
	
	public OpenOperationService(){
		super(Constant.SERVICE_NAME_OPEN);
	}	

	@Override
	protected void onHandleIntent(Intent intent) {
		app = (SDAApplication)this.getApplication();
		om = new OperationManager(getBaseContext());
		
		List<Operation> ops = om.getOperationReady(Operation.OP_OPEN);
		if(ops.size()>0){
			op = ops.get(0);
			om.removeOperation(op.getPath(), Integer.valueOf(op.getAction()));
		}else{
			//TODO Handle the error
			return;
		}
		
		if(app.getSession()!=null && app.getAuthClient()!=null){
			download();
		}else{
			final LiveAuthClient aClient = new LiveAuthClient(this,Config.CLIENT_ID);
			aClient.initialize(Arrays.asList(Config.SCOPES), new LiveAuthListener(){
	            @Override
	            public void onAuthError(LiveAuthException exception, Object userState) {
	            	om.removeOperation(Operation.OP_OPEN);
	            	responseConnectError(OpenOperationService.this.getString(R.string.msg_error_connect));
	            }

	            @Override
	            public void onAuthComplete(LiveStatus status,LiveConnectSession session,Object userState) {
	                if (status==LiveStatus.CONNECTED) {
	                	app.setAuthClient(aClient);
	                	app.setSession(session);
	                    app.setConnectClient(new LiveConnectClient(session));
	                    download();
	                }else{
	                	om.removeOperation(Operation.OP_OPEN);
	                	responseConnectError(OpenOperationService.this.getString(R.string.msg_error_connect));
	                }
	            }
	        });
		}	
		
		
	}
	
	private void download(){
		try {
			JSONObject json = new JSONObject(op.getMeta());
			final SkyDriveObject obj = SkyDriveObject.create(json);	
			File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/SkyDrive");
			if(!dir.exists()) dir.mkdir();										
			File file = new File(Environment.getExternalStorageDirectory().getPath()+"/SkyDrive/"+CUtil.buildFileName(obj));
			if(file.exists()){
				file.delete();
				file.createNewFile();
			}
			app.getConnectClient().downloadAsync(obj.getId()+"/content",file, new LiveDownloadOperationListener(){
				int lastPercent = 0;
				
				@Override
				public void onDownloadCompleted(LiveDownloadOperation operation) {
					sendProgress(true,100,obj.getId(),obj.getParentId());					
				}

				@Override
				public void onDownloadFailed(LiveOperationException exception, LiveDownloadOperation operation) {
					sendProgress(false,0,obj.getId(),obj.getParentId());
				}

				@Override
				public void onDownloadProgress(int totalBytes, int bytesRemaining, LiveDownloadOperation operation) {
					int newPercent = countProgress(totalBytes, bytesRemaining);
					if (newPercent > lastPercent + 5){
						lastPercent = newPercent;
						Log.d(Constant.TAG, "progress: "+newPercent);
						sendProgress(true,newPercent,obj.getId(),obj.getParentId());
					}
					
				}});
		} catch (Exception e) {
			Log.e(Constant.TAG, e.getMessage(), e);
		}
	}
	
	private void responseConnectError(String msg){
		Intent respone = new Intent(Constant.SERVICE_NAME_CONNECT);
		respone.putExtra(Constant.SERVICE_PARAM_ERROR, true);
		respone.putExtra(Constant.SERVICE_PARAM_MSG, msg);
		sendBroadcast(respone);
	}
	
	private int countProgress(long totalBytes, long bytesRemaining) {
		return (int) (((float) (totalBytes - bytesRemaining)) / totalBytes * 100);
    }
	
	private void sendProgress(boolean isSucc,int current, String id, String path){
		Intent intent = new Intent(Constant.SERVICE_NAME_OPEN);
		intent.putExtra(Constant.PARAM_DONE, isSucc);
		intent.putExtra(Constant.PARAM_ID, id);
		intent.putExtra(Constant.PARAM_PATH, path);
		intent.putExtra(Constant.PARAM_PROGRESS, current);
		sendBroadcast(intent);
	}

}
